package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Resource
    private StudentMapper studentMapper;
    @Resource
    private ClazzService clazzService;
    @Override
    public PageResult<Student> stuPage(StudentQueryParam student) {
        Page<Student> stuPage = Page.of(student.getPage(), student.getPageSize());
        //调用page方法查询对应页面数据
        QueryWrapper<Student> wrapper = Wrappers.<Student>query().
                like((student.getName()!=null &&!student.getName().isEmpty()),"name", student.getName())
                .eq((student.getDegree()!=null),"degree", student.getDegree())
                .eq((student.getClazzId()!=null),"clazz_id", student.getClazzId());
        stuPage = page(stuPage,wrapper);
        if(stuPage.getTotal()!=0){
            //补全班级名称数据
            List<Student> stus = stuPage.getRecords();
            Set<Integer> clazzIds = stus.stream().map(Student::getClazzId).collect(Collectors.toSet());
            List<Clazz> clazzes = clazzService.listByIds(clazzIds);
            //转成map集合
            Map<Integer, String> clazzMap = clazzes.stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));
            stus.forEach(stu->{stu.setClazzName(clazzMap.get(stu.getClazzId()));});

            return new PageResult<>(stuPage.getTotal(),stus);
        }
            return null;
    }

    @Override
    public void saveStu(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        //保存学生信息
        save(student);

    }

    @Override
    public void violation(Integer id, Integer score) {
        Student stu = getById(id);
        lambdaUpdate().eq(Student::getId,id).set(Student::getViolationScore,score+stu.getViolationScore());
    }

    @Override
    public void updateStu(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }
}
